<template>
  <div>
    <SearchKuang :obj="data.users" @search="fun" />
    <!-- 用户列表 -->
    <el-table :data="data.users" border style="width: 100%">
      <el-table-column
        align="center"
        prop="name"
        label="序号"
        type="index"
        width="60px"
      />
      <el-table-column align="center" prop="username" label="姓名" />
      <el-table-column align="center" prop="email" label="邮箱" />
      <el-table-column align="center" prop="mobile" label="电话" />
      <el-table-column align="center" prop="role_name" label="角色" />
      <el-table-column align="center" prop="mg_status" label="状态">
        <!-- 状态连接 -->
        <template #default="scope">
          <el-switch
            v-model="scope.row.mg_state"
            @change="statuesChange(scope.row.id, $event)"
            :plain="true"
          />
        </template>
      </el-table-column>
      <!-- 操作 -->
      <el-table-column align="center" prop="op" label="操作" width="220x">
        <template #default="scope">
          <!-- 编辑 -->
          <el-button type="primary" :icon="Edit" @click="editInfo(scope)" />
          <!-- 删除 -->
          <el-button type="danger" :icon="Delete" @click="deleteInfo(scope)" />
          <!-- 设置角色 -->
          <el-popover
            placement="top-start"
            trigger="hover"
            content="分配角色"
            effect="dark"
          >
            <template #reference>
              <el-button
                type="warning"
                :icon="Setting"
                @click="distributeRoleDialog(scope)"
              />
            </template>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <!-- ---------------------------弹出框------------------------------------------------>
    <!-- 编辑 -->
    <el-dialog v-model="editdialogVisible" title="修改用户" width="30%">
      <el-form
        ref="editruleFormRef"
        :model="editRuleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
        :size="large"
        status-icon
      >
        <el-form-item label="用户" prop="name">
          <el-input v-model="data.currentUser.username" disabled />
        </el-form-item>
        <el-form-item label="邮箱名" prop="email">
          <el-input v-model="editRuleForm.email" />
        </el-form-item>
        <el-form-item label="电话" prop="tel">
          <el-input v-model="editRuleForm.tel" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editCancel(editruleFormRef)">取消</el-button>
          <el-button type="primary" @click="editconfirm(editruleFormRef)"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 删除 -->
    <el-dialog v-model="deletedialogVisible" width="30%">
      <p>是否确定删除</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deletedialogVisible = false">再想想</el-button>
          <el-button type="primary" @click="deletConfirm">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 设置角色 -->
    <el-dialog
      v-model="distributeRole"
      title="分配角色"
      width="30%"
      :before-close="handleClose"
    >
      <div>
        <p>当前的用户：{{ data.currentUser.username }}</p>
        <p>当前的角色：{{ data.currentUser.role_name }}</p>
        <p>
          <span>分配角色:</span>
          <el-select
            v-model="roleId"
            class="m-2"
            placeholder="请选择"
            size="large"
          >
            <el-option
              v-for="(v, i) in data.roleLists"
              :key="i"
              :label="v.roleName"
              :value="v.id"
            />
          </el-select>
        </p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="distributeRole = false">取消</el-button>
          <el-button type="primary" @click="distributeRole = false"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <div class="demo-pagination-block">
      <el-pagination
        v-model:currentPage="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="40"
        @size-change="pageSizeChange"
        @current-change="pageCurrentChange"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import SearchKuang from "./SearchKuang.vue";
import { onMounted, reactive, ref, toRef } from "vue";
import { Delete, Edit, Setting } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

import service from "../../until/service";

const roleId = ref("");

// ---------分页---------
const currentPage = ref(1);
const pageSize = ref(10);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);

const pageSizeChange = (val) => {
  console.log(`${val} items per page`);
};
const pageleCurrentChange = (val) => {
  console.log(`current page: ${val}`);
};
// ---------子传父-----------
const fun = (val) => {
  data.users=toRef(val,"users") 
};
// --------获取用户列表--------
interface userdata {
  id: number;
  username: string;
  mobile: string;
  email: string;
  create_time: string;
  mg_status: boolean;
  role_name: string;
}
const data = reactive({
  users: Array<userdata>(),
  currentUser: {},
  roleLists: {},
});

onMounted(() => {
  getUserData();
});

//--------状态连接--------
const mg_status = ref(true);
const statuesChange = (id, type) => {
  service
    .put(`users/${id}/state/${type}`)
    .then((res) => {
      if (res.data.meta.status == 200) {
        ElMessage({
          message: "修改成功",
          type: "success",
        });
      } else {
        ElMessage({
          message: "修改失败",
          type: "error",
        });
      }
    })
    .catch((error) => console.log(error));
};

//----------编辑---------
let id = "";
const editdialogVisible = ref(false);
const formSize = ref("default");
const editruleFormRef = ref<FormInstance>();
const editRuleForm = reactive({
  email: "",
  tel: "",
});
const rules = reactive<FormRules>({
  //规则校验
  email: [
    { required: true, message: "请输入邮箱!", trigger: "blur" },
    {
      type: "email",
      message: "请填写正确的邮箱!",
      trigger: ["blur", "change"],
    },
  ],
  tel: [
    { required: true, message: "请输入手机号!", trigger: ["blur", "change"] },
    {
      trigger: "blur",
      validator: (rule, value, callback) => {
        var passwordreg =
          /^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[3-8]{1})|(18[0-9]{1})|(19[0-9]{1})|(14[5-7]{1}))+\d{8})$/;
        console.log(passwordreg.test(value));
        if (!passwordreg.test(value)) {
          callback(new Error("请输入正确的手机号码哦!"));
        } else {
          callback();
        }
      },
    },
  ],
});

const editInfo = (scope) => {
  editdialogVisible.value = true;
  data.currentUser = toRef(scope, "row");
  id = scope.row.id;
};
// 确认编辑
const editconfirm = (formEl) => {
  formEl.validate((val) => {
    if (!val) return;
    service
      .put(`users/${id}`, {
        id: id,
        email: editRuleForm.email,
        mobile: editRuleForm.tel,
      })
      .then((res) => {
        if (res.data.meta.status == 200) {
          ElMessage({
            message: "修改成功",
            type: "success",
          });
          const index = data.users.findIndex((u) => u.id === res.data.data.id);
          data.users[index] = res.data.data;
          console.log(res.data.data);
          editdialogVisible.value = false;
          formEl.resetFields();
        } else {
          ElMessage({
            message: "修改失败",
            type: "error",
          });
        }
      })
      .catch((error) => console.log(error));
  });
};
// 取消编辑
const editCancel = (formEl) => {
  editdialogVisible.value = false;
  formEl.resetFields();
};

//--------分配角色--------
const distributeRole = ref(false);
const distributeRoleDialog = (scope) => {
  distributeRole.value = true;
  data.currentUser = toRef(scope, "row");
  // 获取分配角色列表
  service
    .get("roles")
    .then((res) => {
      data.roleLists = toRef(res.data, "data");
      console.log(data.roleLists);
    })
    .catch((err) => console.log(err));
};
// 修改角色

// ------删除-------
let deleteId = -99;
const deletedialogVisible = ref(false);
const deleteInfo = (scope) => {
  deletedialogVisible.value = true;
  deleteId = scope.row.id;
};
const deletConfirm = () => {
  deletedialogVisible.value = false;
  // console.log(deleteId);
  service
    .delete(`users/${deleteId}`)
    .then((res) => {
      // console.log(res.data);
      if (res.data.meta.status == 200) {
        ElMessage({
          message: "删除成功",
          type: "success",
        });
        const deleteIndex = data.users.findIndex(
          (item) => item.id === deleteId
        );
        // let newdata = [...data.users];
        data.users.splice(deleteIndex, 1);
        // data.users = newdata;
        // console.log(newdata);
      } else {
        ElMessage({
          message: "删除失败",
          type: "error",
        });
      }
    })
    .catch((error) => console.log(error));
};
// -----封装------
const getUserData = () => {
  service
    .get("users", {
      params: { pagenum: currentPage.value, pagesize: pageSize.value },
    })
    .then((res) => {
      data.users = res.data.data.users
      console.log(res.data.data.users);
    })
    .catch((error) => console.log(error));
};
// ------封-------
</script>


<style scoped>
/* 分页 */
.demo-pagination-block {
  margin-top: 20px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>